package org.sample.springbootredis.service;

import org.sample.springbootredis.client.DatabaseUserClient;
import org.sample.springbootredis.client.model.DateDTO;
import org.sample.springbootredis.client.model.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CacheUserService {

	private static final Logger LOGGER = LoggerFactory.getLogger(CacheUserService.class);

	@Autowired
	private DatabaseUserClient client;

	public List<UserDTO> findAllUsers() {
		return client.findAll();
	}

	@Cacheable(value = "userId")
	public UserDTO findUserById(Long id) {
		UserDTO user = client.findById(id);
		LOGGER.debug("Find cached: userId {}", id);
		return user;
	}

	@Cacheable(value = "userName")
	public UserDTO findUserByName(String userName) {
		UserDTO user = client.findByUserName(userName);
		LOGGER.debug("Find cached: userName {}", userName);
		return user;
	}

	@CachePut(value = "userId", key = "#user.id")
	public UserDTO createUserCacheId(UserDTO userDTO) {
		userDTO = client.create(userDTO);
		LOGGER.debug("Put cache: userId {}", userDTO.getId());
		return userDTO;
	}

	@CachePut(value = "userName", key = "#userDTO.userName")
	public UserDTO createUserCacheName(UserDTO userDTO) {
		UserDTO user = client.create(userDTO);
		LOGGER.debug("Put cache: userName {}", userDTO.getUserName());
		return user;
	}

	@CachePut(value = "userId", key = "#user.id")
	public UserDTO updateUserById(UserDTO user) {
		user = client.updateById(user.getId(), user);
		LOGGER.debug("Update cache: userId {}", user.getId());
		return user;
	}

	@CachePut(value = "userName", key = "#userDTO.userName")
	public UserDTO updateUserByName(UserDTO userDTO) {
		UserDTO user = client.updateByName(userDTO.getUserName(), userDTO);
		LOGGER.debug("Update cache: userName {}", userDTO.getUserName());
		return user;
	}

	@CacheEvict(value = "userId")
	public void deleteUserById(Long id) {
		client.deleteById(id);
		LOGGER.debug("Evict cache: userId {}", id);
	}

	@CacheEvict(value = "userName")
	public void deleteUserByName(String userName) {
		client.deleteByName(userName);
		LOGGER.debug("Evict cache: userName {}", userName);
	}

	public List<UserDTO> findByCreatedDate(String createdDate) {
		DateDTO createdDateDTO = new DateDTO();
		createdDateDTO.setDate(createdDate);
		return client.findByCreatedDate(createdDateDTO);
	}

}
